#!/usr/bin/env bash
set -e

# Usage:
# SONATYPE_USER=<sonatype user> SONATYPE_PW=<sonatype pw> PGP_PW=<pgp pw> PGP_SECRET=<pgp secret> ./sbtPublish <publish cmd>

# Release command:
RELEASE_CMD="${1:?Missing publish command}"

# Make sure required environment variable are set
: "${SONATYPE_USER:?not set}"
: "${SONATYPE_PW:?not set}"
: "${PGP_PW:?not set}"
: "${PGP_SECRET:?is not set}"

if [ ! "$NIGHTLYBUILD" = "yes" ] && [ ! "$RELEASEBUILD" = "yes" ]; then
    echo "Neither NIGHTLYBUILD nor RELEASEBUILD env var set to \"yes\""
    exit 1
fi

# Setup gpg (disabled, we use bouncycastle instead)
# export GPG_TTY="$(tty)"
# echo "$PGP_SECRET" | gpg --batch --import

# Setup bouncycastle instead of gpg to do signing, because gpg explodes when
# doing too many signing requests in parallel (https://github.com/sbt/sbt-pgp/issues/168)
mkdir -p "/root/.sbt/gpg"
echo "$PGP_SECRET" > "/root/.sbt/gpg/secring.asc"

# run sbt with the supplied arg
SBT="$(cd "$(dirname "${BASH_SOURCE[0]}")" >& /dev/null && pwd)/sbt"
"$SBT" "$RELEASE_CMD"
